<template>
  <div class="kva-container">
    <div class="kva-contentbox">
      <home-page-header>
        <div class="kva-form-search">
          <el-form class="search-form" :inline="true" :model="queryParams" ref="searchForm">
            <el-form-item>
              <el-button
                type="danger"
                icon="Delete"
                v-if="selectIds.length > 0"
                style="margin-right: 5px"
                @click="handleBatchRemove"
              >
                批量删除
              </el-button>
              <el-button type="primary" icon="Plus" @click="handleAdd">添加广告</el-button>
            </el-form-item>
            <el-form-item prop="keyword">
              <el-input v-model="queryParams.keyword" placeholder="广告名称" maxlength="100" clearable />
            </el-form-item>
              <el-form-item label="广告商：" prop="advertiserId">
                <el-select
                  style="width: 150px"
                  v-model="queryParams.advertiserId"
                  @change="handleSearch"
                  class="m-2"
                  clearable
                  placeholder="请选择广告商"
                >
                  <el-option v-for="item in advertment" :key="item.id" :label="item.nickname" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="广告类型" prop="type">
                <el-select
                  style="width: 150px"
                  v-model="queryParams.type"
                  @change="handleChangeType"
                  class="m-2"
                  clearable
                  placeholder="请选择广告类型"
                >
                  <el-option
                    v-for="item in functionTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="启用状态" prop="status">
                <el-select
                  style="width: 150px"
                  v-model="queryParams.status"
                  class="m-2"
                  placeholder="请选择启用状态"
                  clearable
                  @change="handleSearch"
                >
                  <el-option
                    v-for="item in [
                      { value: 1, label: '启用中' },
                      { value: 0, label: '禁止中' }
                    ]"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            <el-form-item>
              <el-button type="success" icon="Search" @click.prevent="handleSearch">搜索</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="danger" icon="Refresh" @click.prevent="handleReset">重置</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="danger" icon="Delete" @click.prevent="handleOpenRecycle">回收站</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table
          v-loading="tableLoading"
          :data="tableData"
          @selection-change="handleSelectionChange"
          stripe
          border
          height="calc(100vh - 265px)"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column fixed :label="'总数：' + total" width="150" align="center">
            <template v-slot="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed align="center" label="广告封面" width="100">
            <template v-slot="scope">
              <img :src="scope.row.cover" width="60" height="40" />
            </template>
          </el-table-column>
          <el-table-column label="广告名称" prop="name"  width="200" align="center" />
          <el-table-column label="广告商" width="100"  prop="advertiserName" align="center" />
          <el-table-column align="center" width="200" label="广告功能类型">
            <template v-slot="scope">
              <span v-for="item in functionTypeOptions" :key="item.value" >
                <span  v-if="scope.row.type === item.value">{{item.label}} / (编号：{{item.value}})</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column align="center" width="200" label="广告功能类型">
            <template v-slot="scope">
              <el-input-number v-model="scope.row.sorted" @blur="handleStatus(scope.row, 'sorted')"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="有效时间" width="480" align="center">
            <template v-slot="scope">
                <span v-if="scope.row.expired == 1" style="color: red">（已过期）</span>
                <span v-if="scope.row.expired == 2" style="color: #af840c">（未生效）</span>
                <span v-if="scope.row.expired == 0" style="color: green">（生效中）</span>
                <span style="margin-left: 10px">开始: {{ scope.row.startTime }}</span>
                <span style="margin-left: 10px">结束: {{ scope.row.endTime }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" width="100" label="跳转模式">
            <template v-slot="scope">
              <span v-if="scope.row.skipModel === 1" style="margin-left: 10px">无</span>
              <span v-if="scope.row.skipModel === 2" style="margin-left: 10px">链接</span>
            </template>
          </el-table-column>
          <el-table-column label="是否启用"  width="200" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                @change="handleStatus(scope.row, 'status')"
                :active-value="1"
                active-text="启用中"
                inactive-text="已禁止"
                :inactive-value="0"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" align="center" width="240">
            <template #default="scope">
              <el-button icon="edit" type="info" size="small" @click.stop="handleCopy(scope.row)">复制</el-button>
              <el-button
                icon="edit"
                type="primary"
                size="small"
                @click.stop="handleEdit(scope.row)"
                >编辑</el-button
              >
              <el-button  icon="remove" type="danger" @click.stop="handleDel(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="kva-pagination-box center">
          <el-pagination
            :current-page="queryParams.pageNo"
            :page-size="queryParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </home-page-header>
    </div>
    <add-advert ref="addRef" @load="handleSearch"></add-advert>
    <recycle-bin ref="recycleRef" @load="handleLodeData"></recycle-bin>
  </div>
</template>

<script setup>
  import KVA from '@/utils/kva.js'
  import {copyData,findPages, delById, batchDels, updateStatus } from '@/api/advert/advert.js'
  import { getList } from '@/api/advert/advertment.js'
  import AddAdvert from './components/AddAdvert.vue'
  import RecycleBin from './components/RecycleBin.vue'
  const functionTypeOptions = reactive([
    {label: '首页广告', value: 1},
    {label: '课程广告', value: 2},
    {label: '文章广告', value: 3},
    {label: '个人中心广告', value: 4},
    {label: '文章明细广告', value: 5},
    {label: '课程明细广告', value: 6},
    {label: '悬浮广告', value: 7},
    {label: '小册广告', value: 8},
    {label: '小册明细广告', value: 9},
    {label: '专题广告', value: 10},
    {label: '专题明细广告', value:11},
    {label: '个人社区广告', value: 12},
  ])
  // 定义响应式得列表数据容器
  const tableData = ref([])
  const selectIds = ref([])
  let tableDataCopy = []
  const tableLoading = ref(false)
  const pages = ref(0)
  const total = ref(0)
  const searchForm = ref({})
  const advertment = ref([])
  // 编辑添加相关
  const addRef = ref({})
  const recycleRef = ref({})


  const queryParams = reactive({
    pageNo: 1,
    pageSize: 30,
    status: '',
    keyword: '',
    deleted: 0,
    type: 1,
    advertiserId: ''
  })

  // 加载数据
  const handleLodeData = async () => {
    tableLoading.value = true
    const resp = await findPages(queryParams)
    tableLoading.value = false
    tableData.value = resp.data.records
    tableData.value.forEach((advert, index) => {
      const currentDate = new Date()
      const startDate = new Date(advert.startTime)
      const endDate = new Date(advert.endTime)
      if (currentDate < startDate) {
        tableData.value[index].expired = 2
      } else if (currentDate >= startDate && currentDate <= endDate) {
        tableData.value[index].expired = 0
      } else {
        tableData.value[index].expired = 1
      }
      if (currentDate >= startDate && currentDate <= endDate) {
      } else {
      }
    })

    tableDataCopy = [...resp.data.records]
    total.value = resp.data.total * 1
    pages.value = resp.data.pages * 1
  }

  const hanleLoadAdvertMent = async () => {
    const res = await getList()
    advertment.value = res.data
  }

  // 搜索
  const handleSearch = () => {
    queryParams.pageNo = 1
    handleLodeData()
  }

  const handleChangeType = () => {
    handleSearch()
  }

  // 重置
  const handleReset = () => {
    searchForm.value.resetFields()
    handleSearch()
  }

  // 分页size更改
  const handleSizeChange = (size) => {
    queryParams.pageSize = size
    handleLodeData()
  }

  // 分页pageNo更改
  const handleCurrentChange = (pno) => {
    queryParams.pageNo = pno
    handleLodeData()
  }

  // 添加事件
  const handleAdd = () => {
    addRef.value.handleOpen(false,queryParams.type)
  }

  // 编辑
  const handleEdit = (row) => {
    addRef.value.handleOpen(row.id)
  }

  // 删除
  const handleDel = (row) => {
    KVA.confirm('警告', '<strong>您确定要执行此次操作吗？</strong>', { icon: 'success' }).then(async () => {
      const opid = row.id
      await delById(opid)
      KVA.notifySuccess('删除成功!')
      handleLodeData()
    })
  }

  // 更新状态
  const handleStatus = async (row, field) => {
    try {
      await updateStatus(row.id, field, row[field])
      KVA.notifySuccess('操作成功!')
      handleLodeData()
    } catch (e) {
      handleLodeData()
    }
  }

  // 打开回收站
  const handleOpenRecycle = () => {
    recycleRef.value.handleOpen()
  }

  /**
   * 批量删除
   */
  const handleBatchRemove = () => {
    if (selectIds.value && selectIds.value.length == 0) {
      KVA.notifyError('请选择一个项进行操作！')
      return
    }

    KVA.confirm('警告', '<strong>您确定要执行此次【批量删除】操作吗？</strong>', { icon: 'success' }).then(async () => {
      const ids = selectIds.value.join(',')
      await batchDels(ids)
      KVA.notifySuccess('批量删除成功!')
      handleLodeData()
    })
  }

  // 复制一条
  const handleCopy = async (row)=>{
    await copyData(row.id);
    KVA.success("复制成功!!")
    handleLodeData()
  }

  /**
   * 选择删除的元素
   * @param rows
   */
  const handleSelectionChange = (rows) => {
    selectIds.value = rows.map((c) => c.id)
  }

  onMounted(() => {
    handleLodeData()
    hanleLoadAdvertMent()
  })
</script>
